package com.wj.controller;

import com.wj.service.WriteBookService;
import com.wj.tool.utils.HtmlUtils;
import com.wj.tool.utils.JsoupUtil;
import com.wj.tool.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

/**
 * 抓取小说 控制器
 */
@Controller
@RequestMapping("sys")
@Slf4j
public class WriteBookController {

    @Resource
    private WriteBookService writeBookService;


    @RequestMapping(value = "index", method = RequestMethod.GET)
    public String index() {

        return "sys/write_book";
    }

    /**
     * 抓取单本小说
     * @param bookUrl
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "write", method = RequestMethod.POST)
    public Result book_write(@RequestParam("bookUrl") String bookUrl) {
        try {
            // 尝试连接
            boolean result = HtmlUtils.connectUrl(bookUrl);
//            boolean result = JsoupUtil.isConnection(url);
            if (result) {
                // 正式写入
//                writeBookService.insert(bookUrl);
                writeBookService.insert2(bookUrl);
                return new Result(200, "小说地址解析成功!");
            } else {
                log.info("WriteBookController/book_write:地址解析失败");
                return new Result(500, "小说地址解析失败,抓取失败!");
            }
        }catch (Exception e) {
            log.info("单本抓取小说失败"+e);
        }
        return new Result(500, "小说地址解析失败,抓取失败!");
    }

    /**
     * 批量抓取小说
     * @param bookUrls
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "writes", method = RequestMethod.POST)
    public Result book_writes(@RequestParam("bookUrls") String bookUrls) {
        boolean result = JsoupUtil.isConnection(bookUrls);
        if (result) {
            try {
                Document document = JsoupUtil.getDoc(bookUrls);
                Element element = document.select("div.l").first();
                Elements elements = element.select("span.s2");
                for (Element element1 : elements) {
                    String string = element1.select("a").attr("abs:href");
                    writeBookService.insert(string);
                }
            }catch (Exception e){
                log.info("批量抓取小说异常"+e);
            }
            return new Result(200, "小说地址解析成功!");
        } else {
            log.info("WriteBookController/book_writes:地址解析失败");
            return new Result(500, "小说地址解析失败,抓取失败!");
        }
    }
}